// @Author : zaniu(zzaniu@126.com)
// @Time   : 2021/9/5 21:32
// @Desc   :
//
//                   _ooOoo_
//                  o8888888o
//                  88" . "88
//                  (| -_- |)
//                  O\  =  /O
//               ____/`---'\____
//             .'  \\|     |//  `.
//            /  \\|||  :  |||//  \
//           /  _||||| -:- |||||-  \
//           |   | \\\  -  /// |   |
//           | \_|  ''\---/''  |   |
//           \  .-\__  `-`  ___/-. /
//         ___`. .'  /--.--\  `. . __
//      ."" '<  `.___\_<|>_/___.'  >'"".
//     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//     \  \ `-.   \_ __\ /__ _/   .-` /  /
// =====`-.____`-.___\_____/___.-`____.-'=====
//                   `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//           佛祖保佑       永无BUG
//
package user

import (
	"context"
	"distributedTransaction/client/conf"
	"distributedTransaction/proto2go"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"io/ioutil"
	"net/http"
)

type userInfo struct {
	User string `json:"user"`
	Pwd  string `json:"pwd"`
}

var ret = gin.H{"message": "RPC调用失败", "token": ""}

func Login(ctx *gin.Context) {
	body, _ := ioutil.ReadAll(ctx.Request.Body)
	user := userInfo{}
	err := json.Unmarshal(body, &user)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"message": "请求参数错误", "token": ""})
		return
	}
	fmt.Println("user = ", user.User, ", pwd = ", user.Pwd)
	if len(user.User) > 0 && len(user.Pwd) > 0 {
		rpcServerInfo, err := conf.GetOneRpcServerInfo(conf.GlobalUserServices)
		if err != nil {
			panic(err)
		}
		fmt.Printf("rpcServerInfo.Ip = %s, rpcServerInfo.Port = %d\n", rpcServerInfo.Ip, rpcServerInfo.Port)
		userCoon, err := grpc.Dial(fmt.Sprintf("%s:%d", rpcServerInfo.Ip, rpcServerInfo.Port), grpc.WithInsecure())
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, ret)
			return
		}
		defer userCoon.Close()
		userClient := proto2go.NewUserClient(userCoon)
		login, err := userClient.Login(context.Background(), &proto2go.LoginRequest{UserName: user.User, PassWd: user.Pwd})
		if err != nil {
			st, ok := status.FromError(err)
			if ok && st.Code() == codes.NotFound {
				ctx.JSON(http.StatusNotFound, gin.H{"message": "用户名或密码错误", "token": ""})
			} else {
				ctx.JSON(http.StatusInternalServerError, ret)
			}
			return
		}
		ctx.JSON(http.StatusOK, gin.H{"message": login.Message, "token": login.Token})
	} else {
		ctx.JSON(http.StatusBadRequest, gin.H{"message": "用户名和密码都是必填的", "token": ""})
	}
}
